package com.karaoke.android.library.mvvm

import android.app.TabActivity
import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.os.Bundle
import android.support.annotation.Nullable
import com.trello.rxlifecycle.LifecycleProvider
import com.trello.rxlifecycle.LifecycleTransformer
import com.trello.rxlifecycle.RxLifecycle
import com.trello.rxlifecycle.android.ActivityEvent
import com.trello.rxlifecycle.android.RxLifecycleAndroid
import rx.Observable
import rx.subjects.BehaviorSubject

/**
 * Created by Administrator on 2017/4/1.
 */

abstract class MvvmTabActivity<out VM : ActivityViewModel> : TabActivity(), LifecycleProvider<ActivityEvent>
{
    private val lifecycleSubject = BehaviorSubject.create<ActivityEvent>()

    abstract val viewModel: VM

    override fun lifecycle(): Observable<ActivityEvent>
    {
        return lifecycleSubject.asObservable()
    }

    override fun <T> bindUntilEvent(event: ActivityEvent): LifecycleTransformer<T>
    {
        return RxLifecycle.bindUntilEvent<T, ActivityEvent>(lifecycleSubject, event)
    }

    override fun <T> bindToLifecycle(): LifecycleTransformer<T>
    {
        return RxLifecycleAndroid.bindActivity<T>(lifecycleSubject)
    }

    override fun onCreate(@Nullable savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        lifecycleSubject.onNext(ActivityEvent.CREATE)
        viewModel.onCreate()
    }

    override fun onStart()
    {
        super.onStart()
        lifecycleSubject.onNext(ActivityEvent.START)
        viewModel.onStart()
    }


    override fun onResume()
    {
        super.onResume()
        lifecycleSubject.onNext(ActivityEvent.RESUME)
        viewModel.onResume()
    }

    override fun onPause()
    {
        super.onPause()
        lifecycleSubject.onNext(ActivityEvent.PAUSE)
        viewModel.onPause()
    }

    override fun onDestroy()
    {
        super.onDestroy()
        lifecycleSubject.onNext(ActivityEvent.DESTROY)
        viewModel.onDestroy()
    }

    override fun onStop()
    {
        super.onStop()
        lifecycleSubject.onNext(ActivityEvent.STOP)
        viewModel.onStop()
    }
}
